package main

import (
	"context"
	"fmt"
	"time"

	"github.com/CognitionFoundry/gohfc"
)

func say() {
	fmt.Println(time.Now())
}

func main() {
	// client, err :=
	client, err := newClient()
	if err != nil {
		fmt.Println(err)
		return
	}
	identity, err := newIdentity()
	if err != nil {
		fmt.Println(err)
		return
	}
	identity.MspId = "Org1MSP"

	go func() {
		eventFilteredBlock(client, identity)
	}()

	// query(client, identity, "abf")
	time.Sleep(time.Hour)
}

func eventFilteredBlock(client *gohfc.FabricClient, identity *gohfc.Identity) {

	ch := make(chan gohfc.EventBlockResponse)
	ctx, cancel := context.WithCancel(context.Background())
	err := client.ListenForFullBlock(ctx, *identity, "peer0", "mychannel", ch)
	if err != nil {
		fmt.Println(err)
		cancel()
	}
	for d := range ch {
		fmt.Println("get event")
		fmt.Println(d)
	}
}

func query(client *gohfc.FabricClient, identity *gohfc.Identity, key string) {
	chaincode := &gohfc.ChainCode{
		ChannelId: "mychannel",
		Name:      "xbag",
		Type:      gohfc.ChaincodeSpec_GOLANG,
		Version:   "1.0",
		Args:      []string{"GetState", key},
	}

	result, err := client.Query(*identity, *chaincode, []string{"peer0.org1", "peer0.org2"})
	if err != nil {
		fmt.Println(err)
		return
	}

	for _, res := range result {
		fmt.Println(res.PeerName)
		fmt.Println(res.Error)
		fmt.Println(res.Response)
	}

	invokeC := &gohfc.ChainCode{
		ChannelId: "mychannel",
		Name:      "xbag",
		Type:      gohfc.ChaincodeSpec_GOLANG,
		Version:   "1.0",
		Args:      []string{"PutState", "new_sdk", "value"},
	}

	re, err := client.Invoke(*identity, *invokeC, []string{"peer0.org1"}, "orderer0")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(re.Status)
	fmt.Println(re.TxID)

}

func newClient() (*gohfc.FabricClient, error) {
	gohfc.NewFabricClientFromConfig(config)
	return gohfc.NewFabricClient("./sdk_config.yaml")
}

func newIdentity() (*gohfc.Identity, error) {
	// pk := "crypto-config/peerOrganizations/org1.xbag.nlchain.com/users/Admin@org1.xbag.nlchain.com/tls/client.crt"
	// sk := "crypto-config/peerOrganizations/org1.xbag.nlchain.com/users/Admin@org1.xbag.nlchain.com/tls/client.key"
	pk := "crypto-config/peerOrganizations/org1.xbag.nlchain.com/users/Admin@org1.xbag.nlchain.com/msp/signcerts/Admin@org1.xbag.nlchain.com-cert.pem"
	sk := "crypto-config/peerOrganizations/org1.xbag.nlchain.com/users/Admin@org1.xbag.nlchain.com/msp/keystore/8dc8ad8220a9b5f259b98d793709ed42861b88c6262e2a57df75d2bb62430f97_sk"
	return gohfc.LoadCertFromFile(pk, sk)
}
